# backend/app/repositories/scholar_repo.py
from sqlalchemy.orm import Session
from typing import Optional, List
from app.models.iaro_career.scholars import Scholar
from app.schema.scholar_schema import ScholarCreate, ScholarUpdate

def get_scholar_by_id(db: Session, scholar_id: str) -> Optional[Scholar]:
    return db.query(Scholar).filter(Scholar.scholar_id == scholar_id).first()

def get_scholars_paginated(db: Session, skip: int = 0, limit: int = 100) -> List[Scholar]:
    return db.query(Scholar).offset(skip).limit(limit).all()

def create_or_update_scholar(db: Session, data: ScholarCreate) -> Scholar:
    scholar = get_scholar_by_id(db, data.scholar_id)
    if scholar:
        for key, value in data.dict(exclude_unset=True).items():
            setattr(scholar, key, value)
    else:
        scholar = Scholar(**data.dict())
        db.add(scholar)
    db.commit()
    db.refresh(scholar)
    return scholar

def delete_scholar(db: Session, scholar_id: str) -> bool:
    scholar = get_scholar_by_id(db, scholar_id)
    if not scholar:
        return False
    db.delete(scholar)
    db.commit()
    return True
